<template>
  <div class="high-light">
    <div v-html="highLightText"></div>
  </div>
</template>
<script>
export default {
  props: {
    text: {
      type: String,
      default: "",
    },
    words:{
      type: Array,
      default: [],
    }
  },
  data() {
    return {
    };
  },
  mounted() {
    console.log(this.words);
  },
  methods: {
    //关键词匹配
    //高亮关键字 text =>内容 words:关键词  tag 被包裹的标签
    highLightKeywords(text, words, tag) {
      tag = tag || "span"; // 默认的标签，如果没有指定，使用span
      let i,
        len = words.length,
        re;
      for (i = 0; i < len; i++) {
        // 正则匹配所有的文本
        re = new RegExp(words[i], "g");
        if (re.test(text)) {
          text = text.replace(
            re,
            "<" + tag + " class='highlight'>$&</" + tag + ">"
          );
        }
      }
      return text;
    },
  },
  computed: {
    highLightText() {
      if (this.text.length > 0) {
        return this.highLightKeywords(this.text, this.words);
      }
    },
  },
};
</script>
<style lang="less">
.highlight {
  color: red;
}
</style>